package com.fwtai.service.core;

import com.fwtai.bean.PageFormData;
import com.fwtai.config.ConfigFile;
import com.fwtai.core.AreaDao;
import com.fwtai.tool.ToolClient;
import com.fwtai.tool.ToolListOrMap;
import com.fwtai.tool.ToolString;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * 省市县区域业务层
 * @作者 田应平
 * @版本 v1.0
 * @QQ号码 444141300
 * @创建日期 2021-01-11 17:05:49
 * @官网 <url>http://www.fwtai.com</url>
 */
@Service
public class AreaService{

  private final AreaDao areaDao;

  private final ThreadPoolTaskExecutor taskExecutor;

  public AreaService(final AreaDao areaDao,final ThreadPoolTaskExecutor taskExecutor){
    this.areaDao = areaDao;
    this.taskExecutor = taskExecutor;
  }

  public String add(final HttpServletRequest request){
    final PageFormData formData = new PageFormData(request);
    final String p_name = "name";
    final String p_level = "level";
    final String p_pid = "pid";
    final String validate = ToolClient.validateField(formData,p_name,p_level);
    if(validate != null)return validate;
    Long pid = formData.getLong(p_pid);
    if(pid == null){
      pid = 0L;
      formData.put("pid",pid);
    }
    return ToolClient.executeRows(areaDao.add(formData));
  }

  public String edit(final HttpServletRequest request){
    final PageFormData formData = new PageFormData(request);
    final String p_kid = "kid";
    final String p_name = "name";
    final String p_level = "level";
    final String validate = ToolClient.validateField(formData,p_name,p_level,p_kid);
    if(validate != null)return validate;
    final String exist_key = areaDao.queryExistById(formData.getString(p_kid));
    if(exist_key == null){
      return ToolClient.createJsonFail("数据不存在,刷新重试");
    }
    return ToolClient.executeRows(areaDao.edit(formData));
  }

  public String queryById(final PageFormData formData){
    final String p_id = "id";
    final String validate = ToolClient.validateField(formData,p_id);
    if(validate != null)return validate;
    return ToolClient.queryJson(areaDao.queryById(formData.getString(p_id)));
  }

  public String delById(final PageFormData formData){
    final String p_kid = "id";
    final String validate = ToolClient.validateField(formData,p_kid);
    if(validate != null)return validate;
    final String kid = formData.getString(p_kid);
    final String exist_key = areaDao.queryExistById(kid);
    if(exist_key == null){
      return ToolClient.createJsonFail("删除失败,数据已不存在");
    }
    return ToolClient.executeRows(areaDao.delById(kid));
  }

  public String delByKeys(final PageFormData formData){
    final String p_ids = "ids";
    final String validate = ToolClient.validateField(formData,p_ids);
    if(validate != null)return validate;
    final String ids = formData.getString(p_ids);
    final ArrayList<String> lists = ToolString.keysToList(ids);
    if(lists == null || lists.size() <= 0){
      return ToolClient.createJsonFail("请选择要删除的数据");
    }
    return ToolClient.executeRows(areaDao.delByKeys(lists),"操作成功","数据不存在,刷新重试");
  }

  public String listData(PageFormData formData){
    try {
      formData = ToolClient.dataTableMysql(formData);
      if(formData == null)return ToolClient.jsonValidateField();
      final HashMap<String,Object> map = areaDao.listData(formData);
      return ToolClient.dataTableOK((List<Object>)map.get(ConfigFile.rows),map.get(ConfigFile.total));
    } catch (Exception e){
      return ToolClient.dataTableException(formData.get("sEcho"));
    }
  }

  public String getListData(final PageFormData formData){
    try {
      final PageFormData params = ToolClient.dataTableMysql(formData);
      if(params == null)return ToolClient.jsonValidateField();
      //异步查询
      final CompletableFuture<List<Object>> asyncListData = CompletableFuture.supplyAsync(() -> areaDao.getListData(params),taskExecutor);
      //异步查询
      final CompletableFuture<Integer> asyncTotal = CompletableFuture.supplyAsync(() -> areaDao.getListTotal(params),taskExecutor);
      //等待查询完成
      return ToolClient.dataTableOK(asyncListData.join(),asyncTotal.join());
    } catch (final Exception ignored){
      return ToolClient.dataTableException(formData.get("sEcho"));
    }
  }

  public String getListArea(String pid,final String selected,final HttpServletRequest request){
    if(selected != null){
      final PageFormData formData = new PageFormData(request);
      final List<HashMap<String,Object>> pullDown = areaDao.getPullDown(formData);//回写编辑时的多级区域列表
      if(formData.containsKey("province_id") && formData.containsKey("city_id")){//验证必要字段
        return ToolClient.queryJson(ToolListOrMap.listGroupRemove(pullDown,"level"));
      }else{
        return ToolClient.jsonValidateField();
      }
    }
    if(pid == null){
      pid = "0";
    }
    return ToolClient.queryJson(areaDao.getListArea(pid));
  }

  public String getAreaOpts(String pid){
    if(pid == null || pid.length() <= 0){
      pid = "0";
    }
    return ToolClient.queryJson(areaDao.getAreaOpts(pid));
  }

  public String addProxy(final Long areaId,final Integer level){
    return CompletableFuture.supplyAsync(()->{
      if(areaId == null || level == null){
        return ToolClient.jsonValidateField();
      }
      final HashMap<String,Object> params = new HashMap<>(3);
      final List<Long> parent = areaDao.getAreaParent(areaId);
      if(parent.size() > 1){
        return ToolClient.createJsonFail("出现多个上级代理,请检查代理商");
      }
      params.put("area_id",areaId);
      params.put("level_value",level);
      return ToolClient.executeRows(areaDao.addProxy(params),"操作成功","所选的区域已设为代理");
    },taskExecutor).join();
  }

  public String getAreaTree(final String kid){
    return CompletableFuture.supplyAsync(()->{
      if(kid != null && kid.length() > 0){
        return ToolClient.queryJson(areaDao.getAreaTree(Long.parseLong(kid)));
      }else{
        return ToolClient.queryJson(areaDao.getAreaTree(0));
      }
    },taskExecutor).join();
  }
}